package servlet;

import com.google.gson.Gson;
import dao.UserDao;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/WechatDemo1")
public class WechatDemo1 extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //设置请求编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        /* 设置响应头允许ajax跨域访问 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星号表示所有的异域请求都可以接受， */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");


        //获取微信小程序get的参数值并打印
        String account = (String) request.getParameter("x");
        String password = (String) request.getParameter("y");
        System.out.println(account + "---->" + password);


        UserDao userDao = new UserDao();
        User user = null;

        try {
            user = userDao.findUserByAccountAndPassword(account,password);

        } catch (Exception e) {
//            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        Map<String,Object> result = new HashMap<String, Object>();
        result.put("data",user);


        String json = new Gson().toJson(result);

        Writer out = response.getWriter();
        out.write(json);
        out.flush();


/*

        //转成json数据
        Map<String, String> result = new HashMap<String, String>();
        result.put("data", account + "-->" + password);
        result.put("msg", "后台已收到");
*/


        //使用Gson类需要导入gson-2.8.0.jar
//        String json = new Gson().toJson(result);
 //       System.out.println(json);

        //返回值给微信小程序
/*        Writer out = response.getWriter();
        out.write(json);
        out.flush();*/


    }
}
